import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

from highlight import getSupportedLang, getSupportedStyles
from pygments import highlight
from pygments.lexers import get_lexer_by_name,guess_lexer,get_all_lexers,find_lexer_class
from pygments.formatters import HtmlFormatter
from pygments.styles import get_all_styles

from robot_main import version

divstyles = 'word-wrap:break-word;white-space: pre;border:1px solid #BBBBBB;font-size: 9pt;\
line-height:125%;margin:10px 0 10px 0;'
prestyles = "white-space:pre-wrap;white-space: -moz-pre-wrap;white-space: \
-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;\
padding:0.99em;"


def makeHighlight(lang,style,content):
    lexer = get_lexer_by_name(lang)
    css = r'<style type="text/css"><!--'
    css += (HtmlFormatter(style=style,
                        cssstyles = divstyles,
                        prestyles = prestyles).get_style_defs('.highlight'))
    css += r'--></style>'  
    
    new = highlight(content,lexer, HtmlFormatter(style=style,
                                                 cssstyles = divstyles,
                                                 prestyles = prestyles))
    
    return new,css
    
class mainpage(webapp.RequestHandler):
    languages = getSupportedLang()
    styles = getSupportedStyles()
    
    def get(self):
        template_values = {
          'languages': mainpage.languages,
          'styles': mainpage.styles,
          'version': version,
          'curlang'   : 'python',
          'curstyle'  : 'default', 
          }

        path = os.path.join(os.path.dirname(__file__),'templates', 'index.html')
        self.response.out.write(template.render(path, template_values))
        
    def post(self):
        content = self.request.get('source', 'no code')
        lang = self.request.get('lang', 'python')
        style = self.request.get('style','default')
        newcontent,css = makeHighlight(lang,style,content)
        template_values = {
                          'languages' : mainpage.languages,      
                          'styles'    : mainpage.styles,              
                          'newcontent': newcontent,   
                          'content'   : content,
                          'curlang'   : lang,
                          'curstyle'  : style,  
                          'css'       : css,  
                          }     
        path = os.path.join(os.path.dirname(__file__),'templates', 'index.html')
        self.response.out.write(template.render(path, template_values))                                        
        
    
if __name__ == '__main__':
    app = webapp.WSGIApplication([
        ('/', mainpage),
    ], debug=True)
    run_wsgi_app(app)

